/***
 * 此js文件中的构造函数、方法用于修复异常api:::
 * 
 * SetInterval Function构造函数 修复setInterval每次定时执行的偏差，适用于倒计时场景
 * 用法：
 * var test = new SetInterval(callback, 1000);  //开始定义倒计时
 * test.$clear(); // 移除
 */


//修复setInterval每次定时执行的偏差，适用于倒计时场景
/**
 * callback: 每次回调执行函数
 * time: 每隔多少时间回调一次
 */
function SetInterval(callback, time) {
  this.start = new Date().getTime();
  this.end;
  this.offset;
  this.loopNum = 0;
  this.timeoutTag = null;
  this.time = time;
  this.callback = callback;
  this.$set(time);
}
SetInterval.prototype.$set = function (_time) {
  var that = this;
  if (this.timeoutTag === undefined) return;
  clearTimeout(this.timeoutTag);
  this.timeoutTag = null;
  that.timeoutTag = setTimeout(function () {
    that.loopNum++;
    that.end = new Date().getTime();
    that.callback();
    that.offset = that.end - that.start - that.time * that.loopNum;
    //console.log("333,,,偏移了" + that.offset);
    if (that.offset > 0) {
      that.$set(that.time - that.offset);
    } else if (that.offset < 0) {
      that.$set(that.time + that.offset);
    } else {
      that.$set(that.time);
    }
  }, _time);
};
SetInterval.prototype.$clear = function () {
  clearTimeout(this.timeoutTag);
  //便于拦截区分，此处必须设置为undefined
  this.timeoutTag = undefined;
};

export {
  SetInterval
}
